package com.cml.sqlversionupgradestarter.service;

import cn.hutool.db.sql.SqlExecutor;
import com.cml.sqlversionupgradestarter.context.EnvConstant;
import com.cml.sqlversionupgradestarter.context.SQLVersionUpgradeContext;
import com.cml.sqlversionupgradestarter.entity.SqlUpgradeIndex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * 作者：陈茂林
 * 时间：2022/1/6
 * 描述：
 */
public class SQLVersionUpgradeManager {
    private  Date dbUpgradeTime;

    private SQLVersionUpgradeContext sqlVersionUpgradeContext;
    public SQLVersionUpgradeManager(SQLVersionUpgradeContext sqlVersionUpgradeContext){
        this.sqlVersionUpgradeContext=sqlVersionUpgradeContext;
        this.dbUpgradeTime=this.sqlVersionUpgradeContext.getDbUpgradeTime();
    }

    private Logger logger= LoggerFactory.getLogger(SQLVersionUpgradeManager.class);
    public void upgrade(){
        this.load();//加载
        this.expression();//解析重构
        try {
            this.exec();//执行
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("sql升级失败");
            logger.error(e.getMessage());
        }
    }

    private void load(){
        File sqlUpgradDir = new File(EnvConstant.SQL_UPGRAD_FILE_PATH);
        if(sqlUpgradDir.exists()){
            File[] files = sqlUpgradDir.listFiles();
            for (File file:files) {
                SqlExpression sqlExpression= null;
                if(EnvConstant.SQL_UPGRAD_INDEX_FILE.equals(file.getName())){
                    sqlExpression =new SqlVersionIndexSqlExpression(sqlVersionUpgradeContext,file);
                }else{
                    sqlExpression =new SqlUpgradeSentenceSqlExpression(sqlVersionUpgradeContext,file);
                }
                sqlExpression.interpret();
            }
        }
    }

    private void expression(){
        sqlVersionUpgradeContext.getSqlUpgradeContext().sqlUpgradeContextBuild();
    }

    private void exec() throws Exception {
       Date curVersionDate= sqlVersionUpgradeContext.getSqlVersionContextService().getCurVersionDate();
       if(curVersionDate==null){
           if(dbUpgradeTime != null){
               curVersionDate = dbUpgradeTime;
           }else{
               logger.info("请配置开始时间参数参数：db.upgrade.time");
               return;
           }
       }

       List<SqlUpgradeIndex> sqlUpgradeIndexList=sqlVersionUpgradeContext.getSqlUpgradeContext().getSqlUpgradeIndexList();
        for (int i = 0; i <sqlUpgradeIndexList.size(); i++) {
            SqlUpgradeIndex sqlUpgradeIndex = sqlUpgradeIndexList.get(i);
            if(curVersionDate== null || sqlUpgradeIndex.getDate().compareTo(curVersionDate) == 1){

                sqlUpgradeIndex.getSqlUpgradeVersion().getSqlList().forEach(sql->{
                    try {
                        logger.info("执行升级时间："+sqlUpgradeIndex.getDate());
                        logger.info("执行升级sql："+sql);
                        SqlExecutor.execute(sqlVersionUpgradeContext.getJdbcConnManager().getConnection(), sql.toString());
                    } catch (SQLException e) {
                        logger.error("错误sql语句："+sql);
                        logger.error(e.getMessage());
                    }
                });
                try {
                    sqlVersionUpgradeContext.getSqlVersionContextService().setCurVersionDate(sqlUpgradeIndex.getDate());
                } catch (SQLException e) {
                    logger.error("sql版本设置错误"+sqlUpgradeIndex.getDate());
                    logger.error(e.getMessage());
                }

            }
        }

    }
}
